#!/bin/bash

set -e          # exit on error
set -o pipefail # exit on pipeline error
set -u          # treat unset variable as error

. "/minioslib" || exit 1

pkg update

KERNEL=""
if [ "${KERNEL_BPO}" = "true" ]; then
    BPO="-t ${DISTRIBUTION}-backports"
    KERNEL_VERSION="6.5"
else
    BPO=""
    KERNEL_VERSION="6.1"
fi

if [ "${DISTRIBUTION_TYPE}" = "debian" ]; then
    if [ "${KERNEL_AUFS}" = "true" ] && { [ "${DISTRIBUTION_PHASE}" = "current" ] || [ "${DISTRIBUTION_PHASE}" = "future" ]; }; then
        KERNEL_IMAGE="linux-image-${KERNEL_VERSION}-mos-${KERNEL_ARCH}"
    else
        if [ "${KERNEL_TYPE}" = "default" ]; then
            KERNEL_IMAGE="linux-image-${KERNEL_ARCH}"
        else
            KERNEL_IMAGE="linux-image-${KERNEL_TYPE}-${KERNEL_ARCH}"
        fi
    fi
elif [ "${DISTRIBUTION_TYPE}" = "ubuntu" ]; then
    KERNEL_IMAGE="linux-image-${KERNEL_VERSION}-mos-${KERNEL_ARCH}"
fi

if [ "${KERNEL_TYPE}" != "none" ]; then
    if [ -d "/rootcopy-install" ] && [ -f "/rootcopy-install/$(cd /rootcopy-install && ls linux-image-*${KERNEL_ARCH}.deb | head -n 1)" ]; then
        cd "/rootcopy-install"
        pkg install ./$(ls linux-image-*${KERNEL_ARCH}.deb | head -n 1)
    else
        pkg install "${BPO}" "${KERNEL_IMAGE}"
        apt-mark hold "${KERNEL_IMAGE}"
    fi
fi

if [ -d "/rootcopy-install" ] && [ -f "/rootcopy-install/$(cd /rootcopy-install && ls linux-image-*${KERNEL_ARCH}.deb | head -n 1)" ]; then
    KERNEL="$(dpkg-deb -I /rootcopy-install/$(cd /rootcopy-install && ls linux-image-*${KERNEL_ARCH}.deb | head -n 1) | grep 'Linux kernel, version' | awk '{print $NF}')"
elif [ "${KERNEL_AUFS}" = "true" ] && { [ "${DISTRIBUTION_PHASE}" = "current" ] || [ "${DISTRIBUTION_PHASE}" = "future" ] || [ "${DISTRIBUTION_TYPE}" = "ubuntu" ]; }; then
    KERNEL="$(LANG=C apt-cache depends linux-image-"${KERNEL_VERSION}"-mos-"${KERNEL_ARCH}" 2>/dev/null | grep 'Depends' | sed 's/  Depends: //g' | sed 's/linux-image-//')"
elif [ -f /usr/bin/dpkg-query ] 2>/dev/null; then
    toggle_shell_options e
    KERNEL="$(LANG=C dpkg-query -W -f='${binary:Package}\n' linux-image-* 2>/dev/null | head -n 1 | sed 's/linux-image-//')"
    toggle_shell_options e
elif [ "${KERNEL_TYPE}" = "none" ]; then
    return
else
    KERNEL="$(uname -r)"
fi

toggle_shell_options u
update_config "/minios-build.conf" "KERNEL"
toggle_shell_options u

if [ "${KERNEL_AUFS}" = "true" ] && [ "${DISTRIBUTION_ARCH}" = "amd64" ] && { [ "${DISTRIBUTION_PHASE}" = "current" ] || [ "${DISTRIBUTION_PHASE}" = "future" ]; }; then
    pkg install linux-modules
fi
